const express = require("express");
// 有什么难的，express, mysql, sequelize, zpqy, sequelize-cli 所有技术都只是我的工具而已，怕什么？
const { Chapter,Course } = require("../../models");
const { Op } = require("sequelize");
const { success, fail } = require("../../utils/response");
const {NotFound, BadRequest} = require('http-errors')
const router = express.Router();
// 查询章节-带分页
router.get("/", async (req, res) => {
  try {
    const { pageNum, pageSize } = req.query;
    const conditions = getConditions(req);
    const { count, rows } = await Chapter.findAndCountAll(conditions);
    success(res, "获取成功", {
      pageNum,
      pageSize,
      count,
      list: rows,
    });
  } catch (error) {
    // console.log("自主抛出的错误！", error.name);
    fail(res, error);
  }
});
// 获取参数
function getConditions(req) {
  const { keywords, pageNum, pageSize, CourseId } = req.query;
  const conditions = {
    where: {},
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (keywords) {
    conditions.where.name = {
      [Op.like]: `%${keywords}%`,
    };
  }
  if(CourseId) {
    conditions.where.CourseId = CourseId
  }
  return conditions;
}
// 查询章节-无分页
router.get("/all", async (req, res) => {
  try {
    const { keywords } = req.query;
    let where = {};

    if (keywords) {
      where.title = {
        [Op.like]: `%${keywords}%`,
      };
    }
    const raws = await Chapter.findAll({ where });
    success(res, "获取成功", raws);
  } catch (error) {
    fail(res, error);
  }
});
// 查询章节详情
router.get("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    if(!id) {
      throw BadRequest('章节id不能为空')
    }
    const conditions = {
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'name']
         },
      ]
    }
    const chapter = await Chapter.findByPk(id, conditions);
    if (!chapter) {
      throw NotFound("未找到此章节");
    }
    success(res, "获取成功", chapter);
  } catch (error) {
    fail(res, error);
  }
});
// 增加章节
router.post("/", async (req, res) => {
  try {
    const data = filterWhiteData(req)
    console.log('filterWhiteData data', data);
    
    const chapter = await Chapter.create(data);
    console.log("chapter", chapter);
    success(res, "success", chapter);
  } catch (error) {
    fail(res, error);
  }
});
// 修改章节
router.put("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const chapter = await Chapter.findByPk(id)
    if (!chapter) {
      throw NotFound("未找到此章节");
    }
    const data = filterWhiteData(req)
    const [num] = await Chapter.update(
      data,
      {
        where: {
          id,
        },
      }
    );
    success(res, "success", num);
  } catch (error) {
    fail(res, error);
  }
});
// 删除章节
router.delete("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const chapter = await Chapter.destroy({
      where: { id },
    });
    if (!chapter) {
      throw NotFound("未找到此章节");
    }
    success(res, "success",chapter);
  } catch (error) {
    fail(res, error);
  }
});
// 接受参数白名单，用于新增、修改
function filterWhiteData(req) {
  const {name, content,videoUrl,introduce,CourseId,rank} = req.body
  return {
    name,
    content,
    videoUrl,
    introduce,
    CourseId,
    rank
  }
}

module.exports = router;
